import { ref, onMounted } from "vue"
export const useTreeCatalog = (docName, docLayer) => {
  //定义prop
  const defaultProps = {
    children: "children",
    label: "title",
  }
  //定义数据
  const data = ref([])
  //获取图层目录
  const getFeatures = (docLayer, callback) => {
    var docCatalog = new Zondy.Catalog.MapDoc({
      ip: "localhost",
      port: 6163,
      //设置地图文档的名称
      docName: docLayer,
      //设置地图的索引号
      mapIndex: 0,
    })
    //调用getLayersInfo函数，获取地图文档中所有图层相关信息，在回调函数中处理结果
    docCatalog.getLayersInfo(getListSuccess(callback))
  }
  //获取图层信息的回调
  const getListSuccess = (callback) => {
    return function (data) {
      if (data.succeed) {
        if (data == null) {
          alert("没有获取到矢量地图文档！")
          return
        } else {
          //将一个JSON转换成一个包含JSON文本的字符串
          // let formatData = JSON.stringify(data);
          let children = data.value.map((item) => {
            return { title: item.Name, id: item.LayerIndex }
          })
          if (callback) {
            callback(
              [
                {
                  title: "地图文档",
                  icon: "src/assets/images/map.png",
                  id: "0-0",
                  children: [...children],
                },
              ],
              data
            )
          }
        }
      }
    }
  }
  // 隐藏地图文档的图层，第一个参数是地图文档，第二个参数是要隐藏的图层的layerId
  const hide = (docLayer, layerIDs) => {
    docLayer.setLayerStatus(layerIDs, "hide")
    // console.log(`layerid为${layerIDs} 隐藏`)
    // docLayer.refresh()
  }
  const show = (docLayer, layerIDs) => {
    docLayer.setLayerStatus(layerIDs, "show")
    // console.log(`layerid为${layerIDs} 显示`)
    docLayer.refresh()
  }
  //定义callback
  //定义树形控件图标
  const imagePath = [
    "src/assets/images/area.png",
    "src/assets/images/line.png",
    "src/assets/images/point.png",
  ]
  const callback = (obj) => {
    obj[0]["children"].forEach((item) => {
      if (item.title == "居民区") {
        item.icon = imagePath[0]
      } else if (item.title == "武汉光谷道路") {
        item.icon = imagePath[1]
      } else {
        item.icon = imagePath[2]
      }
    })
    data.value = obj
    // console.log(obj);
  }
  onMounted(() => {
    //实现目录树
    getFeatures(docName, callback)
    // docLayer.value.setLayerStatus([0,1,2,3,4],"hide")
  })
  //切换图层
  const checkedMap = (a, b) => {
    show(docLayer.value, b.checkedKeys)
    // console.log(b.checkedKeys)
  }
  //显隐图层目录
  const showflag = ref(true)
  const hideCatalog = () => {
    showflag.value = !showflag.value
    console.log(showflag.value)
  }
  return { defaultProps, data, checkedMap, hideCatalog, showflag, getFeatures }
}
